package com.ty.framework.web.interceptor;

import com.ty.common.constant.Constants;
import com.ty.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * jwt intercpetor @author Mjg @QQ:2091864671 @Creates by mjg ON 2020/6/25-14:17 @date 2020/06/25
 */
@Slf4j
public class JwtIntercpetor extends HandlerInterceptorAdapter {

  @Resource JwtUtils jwtUtils;
  @Resource RedisTemplate<String, Object> redisTemplate;
  /**
   * 前处理
   *
   * @param request 请求
   * @param response 响应
   * @param handler 处理程序
   * @return boolean* @throws Exception 异常
   */
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=utf-8");
    if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
      response.setStatus(HttpStatus.OK.value());
      return true;
    }
    /**/
    String authorization = request.getHeader("Authorization");
    log.info("authorization-->" + authorization);
    if (!StringUtils.isEmpty(authorization) && authorization.startsWith("Bearer")) {
      String redisToken = (String) redisTemplate.opsForValue().get(Constants.TOKEN);
      if (redisToken == null) {
        throw new RuntimeException("token已过期");
      }
      // 获取token
      String token = authorization.replace("Bearer ", "");
      log.info("token-->" + token);
      if (!redisToken.equals(token)
          || StringUtils.isEmpty(redisToken)
          || StringUtils.isEmpty(token)) {
        throw new RuntimeException("token不正确或失效");
      }
      // 解析token
      Claims claims = jwtUtils.parseJwt(token);
      if (claims == null) {
        log.error("token验证失败");
        throw new RuntimeException("token验证失败");
      }
      return true;
    } else {
      log.error("token为空");
      throw new RuntimeException("token为空");
    }
  }
}
